package com.xauto.pioneer.appuser.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.model.LatLng;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.xauto.pioneer.appuser.R;
import com.xauto.pioneer.appuser.activity.parking.InputCarNumberActivity;
import com.xauto.pioneer.appuser.http.BaseLHttpHandler;
import com.xauto.pioneer.appuser.http.LHttpLib;
import com.xauto.pioneer.appuser.model.ClientSetting;
import com.xauto.pioneer.appuser.model.JSONStatus;
import com.xauto.pioneer.appuser.model.Region;
import com.xauto.pioneer.appuser.scanner.CaptureActivity;
import com.xauto.pioneer.appuser.util.OverlayManager;
import com.xauto.pioneer.appuser.view.PromptDialog;

import net.tsz.afinal.FinalDb;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
 * Created by Administrator on 2018/5/12.
 */

public class ParkingFragment extends Fragment {


    MapView mMapView;
    @Bind(R.id.ivParkingRoadStatus)
    ImageView ivParkingRoadStatus;
    @Bind(R.id.ivParking_location)
    ImageView ivParking_location;
    @Bind(R.id.ivParkingpay)
    ImageView ivParkingpay;
    @Bind(R.id.ivScanpay)
    ImageView ivScanpay;
    Context mContext;
    String telNumber="";
    //当前城市是否开放
    private boolean isOpen = false;
    /**提示框*/
    private PromptDialog promptDialog;
    /**************** 地图相关 ******************/
    private BaiduMap mBaiDuMap;
    /** 定位相关*/
    private LocationClient mLocClient;
    boolean isFirstLoc = true; // 是否首次定位
    /** 所有marker集合*/
    private List<OverlayOptions> overlayOptionsList;
    /** marker 操作管理*/
    private MyOverlayManager myOverlayManager;
    /** 定位成功后，返回的当前定位*/
    public static BDLocation bdLocation;
    public static LatLng currentLatLng;
    /**当前地图缩放等级*/
    private float currentZoom =18;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.ac_tab_parking, container, false);
        mContext = getActivity();
        setupView(view);
        ButterKnife.bind(this, view);
        return view;
    }

    private void setupView(View view) {
        mMapView = (MapView) view.findViewById(R.id.mapParking);
        initData();
    }
    protected void initView() {
//        UserAuth.setVisibility(View.GONE);
        initTelNumber();

    }
    private void initTelNumber(){
        FinalDb finalDb = FinalDb.create(mContext);
        List<ClientSetting> client = finalDb.findAll(ClientSetting.class);
        if (client != null && client.size() >0){
            telNumber = client.get(client.size()- 1).getContact_number();
        }
    }
    protected void initData() {

        // 初始化搜索模块，注册事件监听
        initBaiDuMap();
    }

    @OnClick({R.id.ivScanpay,R.id.ivParkingpay})
    public void onClick(View v){
        switch (v.getId()){
            case R.id.ivParkingpay:
                startActivity(new Intent(mContext, InputCarNumberActivity.class));
                break;
            case R.id.ivScanpay:
                Intent intent = new Intent(mContext, CaptureActivity.class);
                startActivity(intent);
//                IntentIntegrator intentIntegrator = IntentIntegrator.forSupportFragment(ParkingFragment.this).setCaptureActivity(CustomScanActivity.class);
//                intentIntegrator
//                        .setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES)
//                        .setPrompt("将二维码/条码放入框内，即可自动扫描")//写那句提示的话
//                        .setCameraId(0)// 选择摄像头,可使用前置或者后置
//                        .setBeepEnabled(false)// 是否开启声音,扫完码之后会"哔"的一声
//                        .setOrientationLocked(false)//扫描方向固定
//                        .setCaptureActivity(CustomScanActivity.class) // 设置自定义的activity是CustomActivity
//                        .initiateScan(); // 初始化扫描
                break;

        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if(intentResult != null) {
            if(intentResult.getContents() == null) {
                Toast.makeText(getActivity(), "Cancelled", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getActivity(), "Scanned: " + intentResult.getContents(), Toast.LENGTH_LONG).show();
                startActivity(new Intent(mContext, InputCarNumberActivity.class));
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
//        if (intentResult != null) {
//            if (intentResult.getContents() == null) {
//
//            } else {
//                // ScanResult 为获取到的字符串
//                String ScanResult = intentResult.getContents();
//                Log.e("tag","ScanResult = "+ScanResult);
//                Log.e("tag","request = "+requestCode+"   ,  result = "+resultCode+"  ,data = "+data);
////                tvResult.setText(ScanResult);
//            }
//        } else {
//            super.onActivityResult(requestCode, resultCode, data);
//        }
    }

    /** 初始化地图*/
    private void initBaiDuMap() {
        mBaiDuMap = mMapView.getMap();
        //初始化默认西安中心点坐标
        Double lat = 108.953098279;
        Double lng = 34.2777998978;
        LatLng latLng = new LatLng(lat, lng);
        setMyLocationToCenter(latLng,currentZoom);

        // LocationMode.COMPASS 罗盘 FOLLOWING 跟随 NORMAL 普通
//        mBaiDuMap.setMyLocationConfigeration(
//        new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING, true, null)); //传入null当前定位是默认蓝色小点图标
        // 开启定位图层
        mBaiDuMap.setMyLocationEnabled(true);
        // TODO: 2017/6/16 暂时注释
        // 开启交通路况图
//        mBaiDuMap.setTrafficEnabled(isOpenRoadStatus);
        // 定位初始化
        mLocClient = new LocationClient(mContext);
        mLocClient.registerLocationListener(new MyLocationListener());
        initLocation();
        mLocClient.start();
        myOverlayManager = new MyOverlayManager(mBaiDuMap);
        mBaiDuMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
//                Bundle info = marker.getExtraInfo();
//                ParkingSite parkingSite = (ParkingSite) info.getSerializable("parkingSite");
//                takeCurrentBranch(parkingSite);
                return true;
            }
        });
    }

    /** 初始化定位设置*/
    private void initLocation(){
        // LocationClientOption option = new LocationClientOption();
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");
        //可选，默认gcj02，设置返回的定位结果坐标系
        int span = 0;//1000 //todo 根据实际情况是否关闭定位，暂时只定位一次
        //可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setScanSpan(span);
        //可选，设置是否需要地址信息，默认不需要
        option.setIsNeedAddress(true);
        //可选，默认false,设置是否使用gps
        option.setOpenGps(true);
        //可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setLocationNotify(true);
        //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationDescribe(true);
        //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIsNeedLocationPoiList(true);
        //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.setIgnoreKillProcess(false);
        //可选，默认false，设置是否收集CRASH信息，默认收集
        option.SetIgnoreCacheException(false);
        //可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
        option.setEnableSimulateGps(false);
        // 在网络定位中，获取手机机头所指的方向
        option.setNeedDeviceDirect(true);
        mLocClient.setLocOption(option);
    }
    /**
     * 设置我的位置到中心点
     */
    private void setMyLocationToCenter(LatLng latLng,float currentZoom){
        //设置当前位置到地图中间
        MapStatus mapStatus = new MapStatus.Builder().target(latLng).zoom(currentZoom).build();
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mapStatus);
        mBaiDuMap.setMapStatus(mMapStatusUpdate);

    }

    /** 定位SDK监听函数*/
    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(final BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            bdLocation = location;
//            PreferencesUtils.putString(mContext,"ADR",String.valueOf(bdLocation.getAddrStr()));
//            PreferencesUtils.putString(mContext,"LNG",String.valueOf(bdLocation.getLatitude())+":"+String.valueOf(bdLocation.getLongitude()));
            currentLatLng = new LatLng(bdLocation.getLatitude(),bdLocation.getLongitude());

            if(location.getLocType() == BDLocation.TypeNetWorkLocation) {
                loadLocationOpen(location);
            }
            // 构造定位数据
            MyLocationData locData = new MyLocationData.Builder().accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude()).longitude(location.getLongitude()).direction(location.getDirection()).build();

            mBaiDuMap.setMyLocationData(locData); // 设置定位数据
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(18);
                mBaiDuMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                //第一次进入主界面加载数据
                loadLocationOpen(location);
            }
//            mBaiDuMap.setOnMapClickListener(new BaiduMap.OnMapClickListener(){
//                @Override
//                public void onMapClick(LatLng latLng) {
//                    if(carPopupWindow!=null){
//                        if(carPopupWindow.isShowing()){
//                            carPopupWindow.dismiss();
//                            mBaiDuMap.clear();
//                            setMyLocationToCenter(new LatLng(bdLocation.getLatitude(),bdLocation.getLongitude()),currentZoom);
//
//                            currentLatLng = new LatLng(bdLocation.getLatitude(),bdLocation.getLongitude());
//                            loadAll(false,"");}
//                    }}
//                @Override
//                public boolean onMapPoiClick(MapPoi mapPoi) {
//                    return false;
//                }
//            });
//            mBaiDuMap.setOnMapLoadedCallback(new BaiduMap.OnMapLoadedCallback() {
//                @Override
//                public void onMapLoaded() {
//                    myOverlayManager = new MyOverlayManager(mBaiDuMap);
//                }
//            });
//            mBaiDuMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
//                @Override
//                public void onMapStatusChangeStart(MapStatus mapStatus) {
//
//                }
//                @Override
//                public void onMapStatusChangeStart(MapStatus arg0, int arg1) {
//                    // TODO Auto-generated method stub
//
//                }
//                @Override
//                public void onMapStatusChange(MapStatus mapStatus) {
//                    /**
//                     * 地图状态改变结束
//                     * @param status 地图状态改变结束后的地图状态
//                     */
//                    if (!isFirstLoad){
//                        calculateDistance();
//                    }
//                }
//
//                @Override
//                public void onMapStatusChangeFinish(MapStatus mapStatus) {
//                }
//            });
//            logLocationData(location);
        }
        public void onReceivePoi(BDLocation poiLocation) {
        }
    }
    /** 获取当前定位的城市id，查询是否已开通*/
    void loadLocationOpen(final BDLocation location) {
        //判断当前城市是否开通
        new LHttpLib().getRegionCoordinate(mContext, String.valueOf(location.getLongitude()),
                String.valueOf(location.getLatitude()), new BaseLHttpHandler(mContext, true, true) {

                    @Override
                    public void onSuccess(JSONStatus jsonStatus) {
                        super.onSuccess(jsonStatus);
                        Region region = new Region().parse(jsonStatus.data.optJSONObject("region_info"));
                        //从配置文件中读取 当前 region_id 是否已开通
                        if ("0".equals(region.getIs_open())){
                            isOpen = false;
                            if (promptDialog != null){
                                if (promptDialog.isShowing())
                                    promptDialog.cancel();
                                promptDialog = null;
                            }
                            promptDialog = new PromptDialog(mContext,
                                    getString(R.string.business_not_opened),
                                    getString(R.string.business_not_opened_hint),
                                    "确认",getString(R.string.dialogpic_notice),
                                    new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            promptDialog.dismiss();
                                        }
                                    });
                            promptDialog.show();
                        }else {
                            isOpen = true;
//                            loadAll(false,"");
                        }
                    }
                });
    }

    private class MyOverlayManager extends OverlayManager {

        private List<OverlayOptions> overlayOptionsList;

        public void setOverlayOptionsList(List<OverlayOptions> overlayOptionsList) {
            this.overlayOptionsList = overlayOptionsList;
        }

        public MyOverlayManager(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public List<OverlayOptions> getOverlayOptions() {
            return overlayOptionsList;
        }

        @Override
        public boolean onMarkerClick(Marker marker) {
            return false;
        }

        @Override
        public boolean onPolylineClick(Polyline polyline) {
            return false;
        }
    }
}
